package com.bds.tjj.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.stereotype.Service;

import com.bds.tjj.model.Areas;
import com.bds.tjj.model.PropIndex;
import com.bds.tjj.model.User;
import com.bds.tjj.model.common.Result;
import com.bds.tjj.model.common.UserSession;
import com.bds.tjj.utils.Const;
import com.bds.tjj.utils.MD5Util;

/**
 * Created by guoyu on 2018/1/29.
 */
@Service
public class UserService {
	private org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(UserService.class);
	@Resource
	private NutDao dao;

	public Result login(HttpServletRequest request, String username, String password) {
		Result ret = new Result();
		User u = null;

		try {
			HttpSession session = request.getSession();

			session.setAttribute(Const.SESSION_USERNAME, username);
			// session.setMaxInactiveInterval(60 * 120);
			String session_id = session.getId();

			if (password == null || password.equals("")) {
				ret.setResult(Const.FAIL, "请输入密码");
				return ret;
			} else {
				Condition c = Cnd.where("username", "=", username).and("password", "=", MD5Util.MD5(password))
						.and("status", "=", 1);
				u = dao.fetch(User.class, c);
			}

			if (u != null) {

				if (!u.getType().equals("admin")) {
					Date startDate = u.getStart_date();
					Calendar cal = Calendar.getInstance();

					cal.setTime(startDate);

					cal.add(Calendar.DATE, u.getDay());

					Date endDate = cal.getTime();

					Date nowDate = new Date();
					if (nowDate.after(endDate)) {
						ret.setResult(Const.FAIL, "尊敬的" + u.getUsername() + "用户，您的使用已经到期请联系客服充值继续使用");
						return ret;
					}

				}

				dao.update(User.class, Chain.make("session_id", session_id), Cnd.where("id", "=", u.getId()));
				UserSession userSession = new UserSession(u);
				request.getSession().setAttribute(UserSession.sessionKey, userSession);
				// ret.setData(userSession);
				ret.setResult(Const.SUC, "登陆成功");
			} else {
				ret.setResult(Const.FAIL, "用户或者密码错误");
			}
		} catch (Exception e) {
			ret.setResult(Const.FAIL, "检查用户名密码出错");
			LOGGER.error("检查用户名密码出错", e);

		}
		ret.setData(u);
		return ret;
	}

	public Result signUp(HttpServletRequest request, String username, String password, String email) {
		Result ret = new Result();
		User u = null;

		try {
			Condition c = Cnd.where("username", "=", username).and("status", "=", 1);
			u = dao.fetch(User.class, c);

			if (u == null) {
				u = new User();

				u.setCreate_date(new Date());
				u.setStatus(1);
				u.setType("user");
				u.setUsername(username);
				u.setPassword(MD5Util.MD5(password));
				u.setEmail(email);

				dao.insert(u);

				ret.setResult(Const.SUC, "注册成功");
			} else {
				ret.setResult(Const.FAIL, "用户已存在");
			}
		} catch (Exception e) {
			ret.setResult(Const.FAIL, "注册异常");
			LOGGER.error("注册异常", e);

		}
		return ret;
	}

	public User getCurrentUserInfo(HttpServletRequest request) {
		User user = null;

		try {
			Cookie[] cookies = request.getCookies();
			if (cookies == null || cookies.length == 0) {
				return user;
			}

			for (int i = 0; i < cookies.length; ++i) {
				if ("zs_username".equalsIgnoreCase(cookies[i].getName())) {
					String key = cookies[i].getValue();
					if (!StringUtils.isEmpty(key)) {
						Condition c = Cnd.where("username", "=", key).and("status", "=", 1);
						user = dao.fetch(User.class, c);
						if (user != null) {
							return user;
						}
					}
				}
			}
		} catch (Exception e) {
			// logger.error(var6.getMessage(), new Throwable(var6));
		}

		return user;
	}

	// 根据session获取
	public User getCurrentUserInfoBySession(HttpServletRequest request) {
		User user = null;
		String key = (String) request.getSession().getAttribute("username");
		if (!StringUtils.isEmpty(key)) {
			Condition c = Cnd.where("username", "=", key).and("status", "=", 1);
			user = dao.fetch(User.class, c);
			if (user != null) {
				return user;
			}
		}
		return user;
	}

	// 修改个人信息
	public boolean updateUserInfo(String username, String password, String phone_number, String email) {
		try {
			// 改资料
			if (password == null) {
				dao.update(User.class, Chain.make("phone_number", phone_number).add("email", email),
						Cnd.where("username", "=", username));
			} else { // 改密码
				dao.update(User.class, Chain.make("password", MD5Util.MD5(password)),
						Cnd.where("username", "=", username));
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public List<PropIndex> getDataSelect() {
		return dao.query(PropIndex.class,
				Cnd.where("type", "<>", "new").and("status", "=", 1).orderBy("cn_name", "asc"));
	}

	public List<PropIndex> getDataSelect(String type) {
		return dao.query(PropIndex.class,
				Cnd.where("chart_type", "=", type).and("status", "=", 1).orderBy("en_name", "asc"));
	}

	public List<PropIndex> getDataSelect(String type, String tabName) {
		return dao.query(PropIndex.class, Cnd.where("chart_type", "=", type).and("tab_name", "=", tabName)
				.and("status", "=", 1).orderBy("index_order", "asc"));
	}

	public List<PropIndex> getDataAreaSelect(String type, String tabName) {
		return dao.query(PropIndex.class, Cnd.where("chart_type", "=", type).and("is_area", "=", 1)
				.and("tab_name", "=", tabName).and("status", "=", 1).orderBy("index_order", "asc"));
	}

	public List<String> getTabNames() {
		Sql sql = Sqls.create("SELECT tab_name,tab_order FROM T_PROP_INDEX "
				+ "WHERE type<>'new' AND status=1 GROUP BY tab_name,tab_order ORDER BY tab_order");
		sql.setCallback(new SqlCallback() {
			public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
				List<String> list = new LinkedList<String>();
				while (rs.next()) {
					list.add(rs.getString(1));
				}
				return list;
			}
		});
		dao.execute(sql);
		return sql.getList(String.class);
	}

	public String getAreas() {
		return dao.fetch(Areas.class).getAreas();
	}
}
